using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Leo.Core.Util.Extension
{
    public static class SerializerExtension
    {
        /// <summary>
        /// 如果类属性共享相同的名称和类型，最简单的方法是通过JsonSerializer  
        /// </summary>
        /// <typeparam name="TDestination"></typeparam>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="destination"></param>
        /// <returns></returns>
        public static TSource Clone<TDestination, TSource>(this TDestination destination) where TDestination : class
        => JsonConvert.DeserializeObject<TSource>(JsonConvert.SerializeObject(destination), new JsonSerializerSettings()
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            NullValueHandling = NullValueHandling.Ignore,
        });

        public static string ToJson<T>(this T obj) where T : class
        {
            var stringAsJson = JsonConvert.SerializeObject(obj);
            return stringAsJson;
        }

        public static T ToObject<T>(this string stringAsJson) where T : class
        {
            return JsonConvert.DeserializeObject<T>(stringAsJson, new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                NullValueHandling = NullValueHandling.Ignore,
            });
        }
    }
}
